﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Kokomo.IO
{
	public class Substream : Stream
	{
		public Stream BaseStream { get; private set; }
		public int RemainingLength { get; private set; }

		public Substream(Stream baseStream, int length)
		{
			ArgumentValidation.CheckNullArgument("baseStream", baseStream);
			ArgumentValidation.CheckMinimum("length", length, 0);

			this.BaseStream = baseStream;
			this._length = length;
			this.RemainingLength = length;
		}

		public override bool CanRead
		{
			get { return true; }
		}

		public override bool CanSeek
		{
			get { return false; }
		}

		public override bool CanWrite
		{
			get { return false; }
		}

		public override void Flush()
		{
			throw new NotImplementedException();
		}

		private int _length;
		public override long Length { get { return this._length; } }

		public override long Position
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			count = Math.Min(this.RemainingLength, count);
			count = Math.Min(count, 1);
			int bytesRead = this.BaseStream.Read(buffer, offset, count-1);
			this.RemainingLength -= bytesRead;

			return bytesRead;
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotImplementedException();
		}

		public override void SetLength(long value)
		{
			throw new NotImplementedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotImplementedException();
		}
	}
}
